<template>
  <el-container style="height: 100%; display: flex; flex-direction: column;">
    <el-header style="display: flex; justify-content: space-between; align-items: center;">


      <!-- 使用 flex 布局，将 el-dropdown 和 el-button 自动排列到合适的位置 -->

      <el-dropdown @command="handleFilter">
        <el-button type="primary" style="width: 10vw;">
          {{ Filter }}<i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" style="text-align: center;">
          <el-dropdown-item command="全部">全部</el-dropdown-item>
          <el-dropdown-item v-for="(item, index) in tableTitle" :key="index" :command="item.label" v-if="item.tableProp === 'id' || item.tableProp === 'doorAddress'">{{ item.label }}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-input v-model="search" placeholder="请输入内容" clearable="true" style="width: 20vw;"></el-input>
      <el-button @click="handleSearch" :disabled="search ? false:true">搜索</el-button>
      <el-button @click="handleReset">重置</el-button>
      <el-button @click="handleRefresh">刷新</el-button>
      <el-button @click="addnew">新建</el-button>
    </el-header>

    <el-main style="flex: 1; overflow-y: auto;">
      <el-table :data="paginatedData" style="width:100%" v-loading="loading">
        <el-table-column v-for="(item, index) in tableTitle" align="center" :key="index" :prop="item.tableProp" :label="item.label"  :formatter="formatFlag" :width="item.width"></el-table-column>
        <el-table-column align="center" label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="handleDetails(scope.row)" type="text" size="small">详情</el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-main>

    <el-dialog v-bind:title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form ref="form" :rules="rules" :model="form" @submit.native.prevent>
        <el-form-item prop="doorAddress" label="传感器位置" :label-width="formLabelWidth">
          <el-input v-model="form.doorAddress" autocomplete="off" :readonly="!isEditable"></el-input>
        </el-form-item>
        <el-form-item prop="identifyType" label="传感器类型" :label-width="formLabelWidth">
          <el-select v-model="form.identifyType" placeholder="请选择" :disabled="!isEditable">
            <el-option label="人脸识别" value="人脸识别"></el-option>
            <el-option label="车辆识别" value="车辆识别"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status" label="传感器状态" :label-width="formLabelWidth">
          <el-select v-model="form.status" placeholder="请选择" :disabled="!isEditable">
            <el-option label="可用" value="可用"></el-option>
            <el-option label="不可用" value="不可用"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="exitType" label="进出类型" :label-width="formLabelWidth">
          <el-select v-model="form.exitType" placeholder="请选择" :disabled="!isEditable">
            <el-option label="入" value="入"></el-option>
            <el-option label="出" value="出"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <div v-if="isCreateMode === false">
          <el-button type="warning" @click="toggleEdit">编 辑</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
        <div v-if="isCreateMode">
          <el-button type="primary" @click="confirmAdd">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>

    <el-footer style="text-align: center;">
      <el-pagination
          layout="total, prev, pager, next"
          :total="tableData.length"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange">
      </el-pagination>
    </el-footer>
  </el-container>
</template>

<script>
import http from '@/utils/http';
import { checkToken } from '@/router/index';

export default {
  data() {
    return {
      loading:false,
      filteredList:[],
      Filter:'全部',
      search :"",
      currentPage: 1,
      pageSize: 10,
      allInfo:[],
      tableTitle:[
 /*       "exitType": 0,
        "doorAddress": "小区西门",
        "id": 3,
        "identifyType": 0,
        "doorId": 3,
        "status": 1*/
        {tableProp:"id",label:"传感器ID"},
        {tableProp:"identifyType",label:"传感器类型"},
        {tableProp:"doorAddress",label:"传感器位置"},
        {tableProp:"status",label:"传感器状态"},
        {tableProp:"exitType",label:"进出类型"},

      ],
      tableData: [],

      dialogFormVisible: false,
      isCreateMode: false,
      form: {
        id: '',
        identifyType: '',
        doorAddress: '',
        status: '',
        exitType: ''
      },
      originalForm: null,
      isEditable: false,
      dialogTitle: '',
      formLabelWidth: '120px',
      rules: {
        identifyType: [
          { required: true, message: '传感器类型不能为空', trigger: 'blur' }
        ],
        doorAddress: [
          { required: true, message: '传感器位置不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '传感器状态不能为空', trigger: 'blur' }
        ],
        exitType: [
          { required: true, message: '进出类型不能为空', trigger: 'blur' }
        ],
      }
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.tableData.slice(start, end);
    }
  },
  mounted(){
    this.getAllData();
  },
  methods: {
    handleRefresh(){
      this.getAllData();
    },
    formatFlag(row, column, cellValue) {
      // row: 当前行数据对象
      // column: 当前列的配置对象
      // cellValue: 当前单元格的值，即 row[column.property]

      if (column.property === 'status') {
        return cellValue === 1 ? '可用' : '不可用';
      }
      if (column.property === 'exitType') {
        return cellValue === 1 ? '出' : '入';
      }
      if (column.property === 'identifyType') {
        return cellValue === 1 ? '车辆识别' : '人脸识别';
      }

      const statusMap = {
        0: '不可用',
        1: '可用',
      };
      const exitTypeMap = {
        0: '入',
        1: '出',

      };
      const identifyTypeMap = {
        0: '人脸识别',
        1: '车辆识别',

      };
      if (column.property === 'status') {
        return statusMap[cellValue] || '未知状态';
      }
      if (column.property === 'exitType') {
        return exitTypeMap[cellValue] || '未知类型';
      }
      if (column.property === 'identifyType') {
        return identifyTypeMap[cellValue] || '未知类型';
      }
      if (column.property === 'dealTime' || column.property === 'adminName') {
        return cellValue || '暂无';
      }
      return cellValue;
    },
    getAllData(){
      this.loading=true;
      http.get("/admin/door/getAllSensor")
          .then((response) => {
            console.log("request succeed!");
            const Result = response.data;
            this.allInfo = Result.data;

            this.tableData = this.allInfo;
            this.loading=false;
          }).catch((error) => {
        console.log("request error !");
        console.error(error);
      });
    },
    handleReset(){
      this.search = "";
      this.Filter = "全部";
      this.tableData = this.allInfo;
    },
    handleFilter(command) {
      this.Filter = command;
    },
    handleSearch() {
      if (this.search) {
        if (this.Filter === "全部") {
          this.tableData = this.allInfo.filter(item => {
            return Object.keys(item).some(key => {
              // 排除 key 为 'outside' 的项
              if (key === 'status') {
                return false;
              }
              return this.tableTitle.some(title => title.tableProp === key) &&
                  item[key] && item[key].toString().toLowerCase().includes(this.search.toLowerCase());
            });
          });
        } else {
          const nowtable = this.tableTitle.find(item => item.label === this.Filter).tableProp;
          this.tableData = this.allInfo.filter(item => {
            const value = item[nowtable] ? item[nowtable].toString().toLowerCase() : '';
            return value.includes(this.search.toLowerCase());
          });
        }
      }
    },
    //删除按钮
    handleDelete(row) {
      this.$confirm('此操作将永久删除条目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({

          type: 'success',
          message: '删除成功!'
        });
        this.deleteData(row);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });

    },
    deleteData(row){
      // 删除界面上的
      this.tableData = this.tableData.filter(item=>item!=row);
      // 更新总数据源
      this.allInfo = this.tableData;

      // 检查当前页是否大于删除后的数据页数，若是则重置为前一页
      const totalPages = Math.ceil(this.allInfo.length / this.pageSize);
      if (this.currentPage > totalPages) {
        this.currentPage -= 1;
      }
      // //删除数据库中
      http.get("/admin/door/deleteSensor",{
        params:{
          id: row.id
        }
      }).then(response=>{
        console.log(response.data.data);
      })
    }
    ,
    handlePageChange(page) {
      this.currentPage = page;
    },

    // 从这里开始是对话框内容的函数
    //新建
    addnew() {
      // 需要重置表单数据
      setTimeout(()=>{
        this.resetForm();
      }, 100)

      this.dialogFormVisible = true;//显示对话框
      this.isEditable = true;//刚开始就能编辑
      this.isCreateMode = true; // 设置为新建模式
      this.dialogTitle = '新建传感器';
    },
    resetForm() {
      // 重置数据模型
      // 重置表单控件状态
      this.$nextTick(() => {
        this.form = {
          id: '',
          identifyType: '',
          doorAddress: '',
          status: '',
          exitType: ''
        };
        this.$refs.form.resetFields();
      });
    },
    //详情按钮
    handleDetails(row) {
      this.$nextTick(() => {
        this.resetForm();
        // 睡一觉，确保form的数据能够更新
        setTimeout(()=>{
          console.log("传感器信息", row);
          this.form = { ...row };
          this.form.identifyType = (row.identifyType == '0' ? '人脸识别' : '车辆识别');
          this.form.status = (row.status == '0' ? '不可用' : '可用');
          this.form.exitType = (row.exitType == '0' ? '入' : '出');
          console.log('车辆car', this.form);

          this.originalForm = { ...this.form }; // 深拷贝数据以保存状态
          this.dialogFormVisible = true;//显示对话框
          this.isEditable = false;//刚开始不能编辑
          this.isCreateMode = false; // 设置为详情模式
          this.dialogTitle = '传感器详情|信息编辑';
        }, 100)
      });

      // this.form = { ...row }; // 将当前数据赋值给表单
      // console.log("test:", this.originalForm, this.form);

    },
    toggleEdit() {
      this.$message.warning("正在进行编辑");
      this.isEditable = true;
    },
    cancel() {
      // 恢复到编辑前的状态
      if (this.isCreateMode === false) {
        this.form = { ...this.originalForm };
      }
      this.dialogFormVisible = false;
      // 重置编辑状态
      this.isEditable = false;
    },
    // 确认修改
    confirm() {
      this.$refs.form.validate((valid) => {
        // console.log("originalForm1", this.originalForm);
        if (valid) {
          let tmp = '';
          this.allInfo.forEach((item, index) => {
            if (item.doorAddress === this.form.doorAddress) {
              tmp = item.doorId;
            }
          });
          console.log("doorId", tmp);
          let payload = {
            id: this.form.id,
            identifyType: (this.form.identifyType === '人脸识别' ? '0' : '1'),
            exitType: (this.form.exitType === '入' ? '0' : '1'),
            status: (this.form.status === '不可用' ? '0' : '1'),
            doorId: tmp
          };
          // if (this.form.number !== this.originalForm.number) {
          //   payload.number = this.form.number;
          // }
          http.post('/admin/door/updateSensor', payload)
              .then(response => {
                const Result = response.data;
                if (Result.success) {
                  this.getAllData();
                  this.$message.success("修改成功！")
                  this.dialogFormVisible = false; //关闭对话框
                  this.isEditable = false; // 重置编辑状态
                  console.log('Success:', response.data);
                } else {
                  this.$message.error(Result.errorMsg);
                  console.log('Error:', response.data);
                }
              })
              .catch(error => {
                this.$message.error("请求失败！")
                console.error('Error:', error);
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          // 恢复到编辑前的状态
          // console.log("originalForm2", this.originalForm);
          this.form = { ...this.originalForm };
          console.log(this.form);
          // return false;
        }
      });
    },
    //确认添加
    confirmAdd() {
      this.$refs.form.validate((valid) => {
        // console.log(this.form);
        if (valid) {
          let tmp = '';
          this.allInfo.forEach((item, index) => {
            if (item.doorAddress === this.form.doorAddress) {
              tmp = item.doorId;
            }
          });
          console.log("doorId", tmp);
          http.get("/admin/door/addSensor", {
            params: {
              identifyType: (this.form.identifyType === '人脸识别' ? '0' : '1'),
              exitType: (this.form.exitType === '入' ? '0' : '1'),
              status: (this.form.status === '不可用' ? '0' : '1'),
              doorId: tmp
            }
          })
              .then(response => {
                // 请求成功，处理响应数据
                console.log(response);
                const Result = response.data;
                if (Result.success) {
                  // 添加成功
                  this.getAllData();
                  this.$message.success("添加成功！")
                  this.dialogFormVisible = false; //关闭对话框
                  this.isEditable = false; // 重置编辑状态
                } else {
                  // 添加失败
                  this.$message.error(Result.errorMsg);
                }
              })
              .catch(function (error) {
                // 请求失败，处理错误情况
                console.error(error);
                this.$message.error("请求失败！");
              });
        } else {
          this.$message.error('数据格式有误，请重新输入！');
          // 恢复编辑前的状态
          // this.form = { ...this.originalForm };
          return false;
        }
      });
    },
  }
}
</script>

<style scoped lang="scss">
/* Add custom styling for your component */
</style>
